package com.zl.iot.docking;

import com.zl.iot.docking.builder.ConsumerBuilder;
import com.zl.iot.docking.exception.ZLExcep;
import com.zl.iot.docking.model.AliConsume;
import com.zl.iot.docking.model.AliProductServer;
import com.zl.iot.docking.model.AliServerVO;
import com.zl.iot.docking.model.ModuleStatusVO;
import com.zl.iot.docking.service.AliProductRequest;
import com.zl.iot.docking.service.AliServerRequest;
import com.zl.iot.docking.service.Consumer;
import com.zl.iot.docking.util.AliUtil;
import org.apache.commons.lang3.StringUtils;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;

/**
 * @author chenzy
 * @since 2023/6/26
 **/
public class Demo {
    private final static AliServerVO aliServer = new AliServerVO()
            .setAccessKeyId("阿里云秘钥key")
            .setAccessSecret("阿里云秘钥")
            .setAmqHost("iot-040a05o5.amqp.iothub.aliyuncs.com")
            .setInstanceId("iot-040a05o5")
            .setRegionId("cn-shenzhen")
            .setUid("iot-040a05o5")
            .setCurMachineNum(0)
            .setMaxMachineNum(100)
            .setSysDomain("iot.cn-shenzhen.aliyuncs.com");
    private final static AliProductServer aliProductServer = new AliProductServer()
            .setAliServer(aliServer)
            .setCkey("g7t2thFTCP1")
            .setName("饮水")
            .setConsumerGroupId("DEFAULT_GROUP")
            .setConsumerGroupName("默认消费组");

    public static void main(String[] args) {
        /*获取设备状态*/
        var data=getMachineStatus();
        /*向设备发送消息*/
        send2Ali();
//        /*订阅消息:接收设备上报数据*/
//        comsumer();
        System.out.println(data);
    }

    public static void addProduct(){
        AliServerRequest.build(aliServer).addProduct("产品名称","产品名称描述");
    }
    /*上行:从阿里云amq订阅消息*/
    public static void comsumer() {
        var aliConsume = new AliConsume().setConsumeNum(4)
                .setConsumeGroupId(aliProductServer.consumerGroupId)
                .setInstanceId(aliProductServer.instanceId);
        ConsumerBuilder.instance(MyComsumer.class).buildList(aliConsume,aliServer);
    }

    /*下行:向阿里云发送消息*/
    public static void send2Ali() {
        var machineId = "23062006000285A9";
        var contend = "要发送到阿里云的消息";
        AliProductRequest.build(aliProductServer).send(machineId, contend);
    }

    /*从阿里云获取设备状态*/
    public static ModuleStatusVO getMachineStatus() {
        var machineId = "23062006000285A9";
        var contend = "要发送到阿里云的消息";
        return AliProductRequest.build(aliProductServer).getStatusByMachineId(machineId);
    }

    public static class MyComsumer extends Consumer {
        public MyComsumer(AliServerVO aliServer, Connection connection, Destination queue) {
            super(aliServer, connection, queue);
        }

        @Override
        public void consumer(Message message) {
            try {
                var serverName = aliServer.getName();
                var content = new String(message.getBody(byte[].class));
                var qos = message.getIntProperty("qos");
                var topic = message.getStringProperty("topic");
                var generateTime = message.getLongProperty("generateTime");
//                var generateTimeStr = TimeUtil.long2Str(generateTime, TimeFormat.yyyyMMddHHmmssSSS).orElse(null);
                var messageId = message.getStringProperty("messageId");
                logger.info("[" + serverName + "]订阅消息:generateTime={},topic={},messageId={},content={}", generateTime, topic, messageId, content);
                if (StringUtils.isBlank(content)) {
                    /*空消息*/
                    return;
                }
                var topics = topic.split("/");
                if (topics == null || topics.length < 3) {
                    throw ZLExcep.error("消息订阅异常,topic不包含sn和productKey");
                }
//            /as/mqtt/status/ga751VziBbr/9909220100000F1E
                String ckey, machineId;
                if (topics.length == 6 && topics[3].equals("status")) {
                    /*设备上线下线*/
                    ckey = topics[4];
                    machineId = topics[5];
                } else {
                    ckey = topics[1];
                    machineId = topics[2];
                }
                System.out.println("订阅消息:" + message.toString());
            } catch (JMSException e) {
                throw new RuntimeException(e);
            }catch (Throwable e) {
                logger.error("消息订阅失败3", e);
            } finally {
                try {
                    message.acknowledge();
                } catch (JMSException e) {
                    throw ZLExcep.error("消息确认失败3", e);
                }
            }

        }
    }
}
